package com.jnevision.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang3.StringUtils;

public class Ranging {

    public static void main(String[] args) {
        // String start = "山东省济南市历城区荷花街道坝子村";
        // String end = "山东省济南市历下区三庆·齐盛广场";
        //
        // String startLonLat = getLonLat(start);
        // String endLonLat = getLonLat(end);
        //
        // System.out.println(startLonLat);
        // System.out.println(endLonLat);
        // Long dis = getDistance("117.142108,36.681686", "117.142882,36.679452");
        // System.out.println(dis);

        String str = null;

        System.out.println(StringUtils.trim(str).split(",").length);
    }

    public static String getLonLat(String address) {
        // 返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl =
            "http://restapi.amap.com/v3/geocode/geo?key=64489384aae5f612ebfc6b5a43acfd8c&address=" + address;
        String queryResult = getResponse(queryUrl); // 高德接品返回的是JSON格式的字符串

        ResultMap resultMap = JsonMapper.nonDefaultMapper().fromJson(queryResult, ResultMap.class);

        return resultMap.getGeocodes().get(0).getLocation();
    }

    public static double getDistance(String startLonLat, String endLonLat) {
        // 返回起始地startAddr与目的地endAddr之间的距离，单位：米
        // String queryUrl = "http://restapi.amap.com/v3/distance?key=64489384aae5f612ebfc6b5a43acfd8c&origins="
        // + startLonLat + "&destination=" + endLonLat;
        // String queryResult = getResponse(queryUrl);
        //
        // ResultMap resultMap = JsonMapper.nonDefaultMapper().fromJson(queryResult, ResultMap.class);
        //
        // return Long.parseLong(resultMap.getResults().get(0).getDistance());

        String[] location1 = startLonLat.split(",");
        String[] location2 = endLonLat.split(",");

        return BaiduMap.getShortDistance(Double.parseDouble(location1[0]), Double.parseDouble(location1[1]),
            Double.parseDouble(location2[0]), Double.parseDouble(location2[1]));
    }

    private static String getResponse(String serverUrl) {

        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}